import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);


// 导入mui框架的样式
import './lib/mui/css/mui.min.css';
import './lib/mui/css/icons-extra.css';


import { Header, Swipe, SwipeItem } from 'mint-ui';
Vue.component(Header.name, Header);
Vue.component(Swipe.name, Swipe);
Vue.component(SwipeItem.name, SwipeItem);


// 导入vue-resource
import VueResource from 'vue-resource';
Vue.use(VueResource);

// 导入路由模块
import router from './router.js';

import Vuex from 'vuex';
Vue.use(Vuex);
var store = new Vuex.Store({
    state: {
        car: [],
        sortList : []
    },
    mutations: {
        // 商品添加到购物车
        addToCar(state, goodsinfo) {
            var flag = false;

            state.car.some(item => {
                if (item.id == goodsinfo.id) {
                    item.count += goodsinfo.count;
                    flag = true;
                    return true;
                }
            });
            if (!flag) {
                state.car.push(goodsinfo);
            }

            localStorage.setItem('car', JSON.stringify(state.car));
        },
        // 因为要显示购物车的数量，在页面加载时获取用户（若已登录）的购物车数据
        initCarInfo(state, obj) {
            state.car = obj;
            localStorage.setItem('car', JSON.stringify(state.car));
        },
        // 根据购物车增加/减少商品的行为进行数据更新
        undateGoodsInfoCount(state, updateData) {
            state.car.some(item => {
                if (item.id == updateData.goodsid) {
                    item.count = updateData.count;
                    return true;
                }
            });

            localStorage.setItem('car', JSON.stringify(state.car));
        },
        // 移除购物车中的商品
        removeGoodsInfoFromCar(state, goodsid) {
            state.car.some((item, i) => {
                if (item.id == goodsid) {
                    state.car.splice(i, 1);
                    return true;
                }
            });
            localStorage.setItem('car', JSON.stringify(state.car));
        },

        // 获取分类的导航信息
        initSortList(state, initData){            
            state.sortList = initData;
        },
        // 登出清除购物车内容
        clearCarFromSignout(state){
            state.car = [];
        }
    },
    getters: {

        // 计算购物车商品的总数量
        getAllCount(state) {
            var c = 0;
            state.car.forEach(item => {
                c += item.count;
            });
            return c;
        },

        // 计算购物车中选中商品的总价
        getTotalCost(state) {
            var total = 0;
            for (var item of state.car) {
                if (item.selected) {
                    total = total + item.count * item.singleCost;
                }
            }
            return total;
        }
    }
});

// 导入根组件
import app from './App.vue';


// 导入mock
import './mock.js';


var vm = new Vue({
    el: '#app',
    created(){     
    },
    render: c => c(app),
    router,
    store
});